home *** CD-ROM | disk | FTP | other *** search
/ Sprite 1984 - 1993 / Sprite 1984 - 1993.iso / src / cmds / update / regexp.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-02-19  |  27.2 KB  |  1,228 lines

  1. /*
  2.  * regcomp and regexec -- regsub and regerror are elsewhere
  3.  *
  4.  *    Copyright (c) 1986 by University of Toronto.
  5.  *    Written by Henry Spencer.  Not derived from licensed software.
  6.  *
  7.  *    Permission is granted to anyone to use this software for any
  8.  *    purpose on any computer system, and to redistribute it freely,
  9.  *    subject to the following restrictions:
  10.  *
  11.  *    1. The author is not responsible for the consequences of use of
  12.  *        this software, no matter how awful, even if they arise
  13.  *        from defects in it.
  14.  *
  15.  *    2. The origin of this software must not be misrepresented, either
  16.  *        by explicit claim or by omission.
  17.  *
  18.  *    3. Altered versions must be plainly marked as such, and must not
  19.  *        be misrepresented as being the original software.
  20.  *
  21.  * Beware that some of this code is subtly aware of the way operator
  22.  * precedence is structured in regular expressions.  Serious changes in
  23.  * regular-expression syntax might require a total rethink.
  24.  */
  25. #include "regexp.h"
  26.  
  27. #define NULL 0
  28.  
  29. /*
  30.  * The "internal use only" fields in regexp.h are present to pass info from
  31.  * compile to execute that permits the execute phase to run lots faster on
  32.  * simple cases.  They are:
  33.  *
  34.  * regstart    char that must begin a match; '\0' if none obvious
  35.  * reganch    is the match anchored (at beginning-of-line only)?
  36.  * regmust    string (pointer into program) that match must include, or NULL
  37.  * regmlen    length of regmust string
  38.  *
  39.  * Regstart and reganch permit very fast decisions on suitable starting points
  40.  * for a match, cutting down the work a lot.  Regmust permits fast rejection
  41.  * of lines that cannot possibly match.  The regmust tests are costly enough
  42.  * that regcomp() supplies a regmust only if the r.e. contains something
  43.  * potentially expensive (at present, the only such thing detected is * or +
  44.  * at the start of the r.e., which can involve a lot of backup).  Regmlen is
  45.  * supplied because the test in regexec() needs it and regcomp() is computing
  46.  * it anyway.
  47.  */
  48.  
  49. /*
  50.  * Structure for regexp "program".  This is essentially a linear encoding
  51.  * of a nondeterministic finite-state machine (aka syntax charts or
  52.  * "railroad normal form" in parsing technology).  Each node is an opcode
  53.  * plus a "next" pointer, possibly plus an operand.  "Next" pointers of
  54.  * all nodes except BRANCH implement concatenation; a "next" pointer with
  55.  * a BRANCH on both ends of it is connecting two alternatives.  (Here we
  56.  * have one of the subtle syntax dependencies:  an individual BRANCH (as
  57.  * opposed to a collection of them) is never concatenated with anything
  58.  * because of operator precedence.)  The operand of some types of node is
  59.  * a literal string; for others, it is a node leading into a sub-FSM.  In
  60.  * particular, the operand of a BRANCH node is the first node of the branch.
  61.  * (NB this is *not* a tree structure:  the tail of the branch connects
  62.  * to the thing following the set of BRANCHes.)  The opcodes are:
  63.  */
  64.  
  65. /* definition    number    opnd?    meaning */
  66. #define    END    0    /* no    End of program. */
  67. #define    BOL    1    /* no    Match "" at beginning of line. */
  68. #define    EOL    2    /* no    Match "" at end of line. */
  69. #define    ANY    3    /* no    Match any one character. */
  70. #define    ANYOF    4    /* str    Match any character in this string. */
  71. #define    ANYBUT    5    /* str    Match any character not in this string. */
  72. #define    BRANCH    6    /* node    Match this alternative, or the next... */
  73. #define    BACK    7    /* no    Match "", "next" ptr points backward. */
  74. #define    EXACTLY    8    /* str    Match this string. */
  75. #define    NOTHING    9    /* no    Match empty string. */
  76. #define    STAR    10    /* node    Match this (simple) thing 0 or more times. */
  77. #define    PLUS    11    /* node    Match this (simple) thing 1 or more times. */
  78. #define    OPEN    20    /* no    Mark this point in input as start of #n. */
  79.             /*    OPEN+1 is number 1, etc. */
  80. #define    CLOSE    30    /* no    Analogous to OPEN. */
  81.  
  82. /*
  83.  * Opcode notes:
  84.  *
  85.  * BRANCH    The set of branches constituting a single choice are hooked
  86.  *        together with their "next" pointers, since precedence prevents
  87.  *        anything being concatenated to any individual branch.  The
  88.  *        "next" pointer of the last BRANCH in a choice points to the
  89.  *        thing following the whole choice.  This is also where the
  90.  *        final "next" pointer of each individual branch points; each
  91.  *        branch starts with the operand node of a BRANCH node.
  92.  *
  93.  * BACK        Normal "next" pointers all implicitly point forward; BACK
  94.  *        exists to make loop structures possible.
  95.  *
  96.  * STAR,PLUS    '?', and complex '*' and '+', are implemented as circular
  97.  *        BRANCH structures using BACK.  Simple cases (one character
  98.  *        per match) are implemented with STAR and PLUS for speed
  99.  *        and to minimize recursive plunges.
  100.  *
  101.  * OPEN,CLOSE    ...are numbered at compile time.
  102.  */
  103.  
  104. /*
  105.  * A node is one char of opcode followed by two chars of "next" pointer.
  106.  * "Next" pointers are stored as two 8-bit pieces, high order first.  The
  107.  * value is a positive offset from the opcode of the node containing it.
  108.  * An operand, if any, simply follows the node.  (Note that much of the
  109.  * code generation knows about this implicit relationship.)
  110.  *
  111.  * Using two bytes for the "next" pointer is vast overkill for most things,
  112.  * but allows patterns to get big without disasters.
  113.  */
  114. #define    OP(p)    (*(p))
  115. #define    NEXT(p)    (((*((p)+1)&0377)<<8) + (*((p)+2)&0377))
  116. #define    OPERAND(p)    ((p) + 3)
  117.  
  118. /*
  119.  * See regmagic.h for one further detail of program structure.
  120.  */
  121.  
  122.  
  123. /*
  124.  * Utility definitions.
  125.  */
  126. #ifndef CHARBITS
  127. #define    UCHARAT(p)    ((int)*(unsigned char *)(p))
  128. #else
  129. #define    UCHARAT(p)    ((int)*(p)&CHARBITS)
  130. #endif
  131.  
  132. #define    FAIL(m)    { regerror(m); return(NULL); }
  133. #define    ISMULT(c)    ((c) == '*' || (c) == '+' || (c) == '?')
  134. #define    META    "^$.[()|?+*\\"
  135.  
  136. /*
  137.  * Flags to be passed up and down.
  138.  */
  139. #define    HASWIDTH    01    /* Known never to match null string. */
  140. #define    SIMPLE        02    /* Simple enough to be STAR/PLUS operand. */
  141. #define    SPSTART        04    /* Starts with * or +. */
  142. #define    WORST        0    /* Worst case. */
  143.  
  144. /*
  145.  * Global work variables for regcomp().
  146.  */
  147. static char *regparse;        /* Input-scan pointer. */
  148. static int regnpar;        /* () count. */
  149. static char regdummy;
  150. static char *regcode;        /* Code-emit pointer; ®dummy = don't. */
  151. static long regsize;        /* Code size. */
  152.  
  153. /*
  154.  * The first byte of the regexp internal "program" is actually this magic
  155.  * number; the start node begins in the second byte.
  156.  */
  157. #define    MAGIC    0234
  158.  
  159.  
  160. /*
  161.  * Forward declarations for regcomp()'s friends.
  162.  */
  163. #ifndef STATIC
  164. #define    STATIC    static
  165. #endif
  166. STATIC char *reg();
  167. STATIC char *regbranch();
  168. STATIC char *regpiece();
  169. STATIC char *regatom();
  170. STATIC char *regnode();
  171. STATIC char *regnext();
  172. STATIC void regc();
  173. STATIC void reginsert();
  174. STATIC void regtail();
  175. STATIC void regoptail();
  176. #ifdef STRCSPN
  177. STATIC int strcspn();
  178. #endif
  179.  
  180. /*
  181.  - regcomp - compile a regular expression into internal code
  182.  *
  183.  * We can't allocate space until we know how big the compiled form will be,
  184.  * but we can't compile it (and thus know how big it is) until we've got a
  185.  * place to put the code.  So we cheat:  we compile it twice, once with code
  186.  * generation turned off and size counting turned on, and once "for real".
  187.  * This also means that we don't allocate space until we are sure that the
  188.  * thing really will compile successfully, and we never have to move the
  189.  * code and thus invalidate pointers into it.  (Note that it has to be in
  190.  * one piece because free() must be able to free it all.)
  191.  *
  192.  * Beware that the optimization-preparation code in here knows about some
  193.  * of the structure of the compiled regexp.
  194.  */
  195. regexp *
  196. regcomp(exp)
  197. char *exp;
  198. {
  199.     register regexp *r;
  200.     register char *scan;
  201.     register char *longest;
  202.     register int len;
  203.     int flags;
  204.  
  205.     if (exp == NULL)
  206.         FAIL("NULL argument");
  207.  
  208.     /* First pass: determine size, legality. */
  209.     regparse = exp;
  210.     regnpar = 1;
  211.     regsize = 0L;
  212.     regcode = ®dummy;
  213.     regc(MAGIC);
  214.     if (reg(0, &flags) == NULL)
  215.         return(NULL);
  216.  
  217.     /* Small enough for pointer-storage convention? */
  218.     if (regsize >= 32767L)        /* Probably could be 65535L. */
  219.         FAIL("regexp too big");
  220.  
  221.     /* Allocate space. */
  222.     r = (regexp *)malloc(sizeof(regexp) + (unsigned)regsize);
  223.     if (r == NULL)
  224.         FAIL("out of space");
  225.  
  226.     /* Second pass: emit code. */
  227.     regparse = exp;
  228.     regnpar = 1;
  229.     regcode = r->program;
  230.     regc(MAGIC);
  231.     if (reg(0, &flags) == NULL)
  232.         return(NULL);
  233.  
  234.     /* Dig out information for optimizations. */
  235.     r->regstart = '\0';    /* Worst-case defaults. */
  236.     r->reganch = 0;
  237.     r->regmust = NULL;
  238.     r->regmlen = 0;
  239.     scan = r->program+1;            /* First BRANCH. */
  240.     if (OP(regnext(scan)) == END) {        /* Only one top-level choice. */
  241.         scan = OPERAND(scan);
  242.  
  243.         /* Starting-point info. */
  244.         if (OP(scan) == EXACTLY)
  245.             r->regstart = *OPERAND(scan);
  246.         else if (OP(scan) == BOL)
  247.             r->reganch++;
  248.  
  249.         /*
  250.          * If there's something expensive in the r.e., find the
  251.          * longest literal string that must appear and make it the
  252.          * regmust.  Resolve ties in favor of later strings, since
  253.          * the regstart check works with the beginning of the r.e.
  254.          * and avoiding duplication strengthens checking.  Not a
  255.          * strong reason, but sufficient in the absence of others.
  256.          */
  257.         if (flags&SPSTART) {
  258.             longest = NULL;
  259.             len = 0;
  260.             for (; scan != NULL; scan = regnext(scan))
  261.                 if (OP(scan) == EXACTLY && strlen(OPERAND(scan)) >= len) {
  262.                     longest = OPERAND(scan);
  263.                     len = strlen(OPERAND(scan));
  264.                 }
  265.             r->regmust = longest;
  266.             r->regmlen = len;
  267.         }
  268.     }
  269.  
  270.     return(r);
  271. }
  272.  
  273. /*
  274.  - reg - regular expression, i.e. main body or parenthesized thing
  275.  *
  276.  * Caller must absorb opening parenthesis.
  277.  *
  278.  * Combining parenthesis handling with the base level of regular expression
  279.  * is a trifle forced, but the need to tie the tails of the branches to what
  280.  * follows makes it hard to avoid.
  281.  */
  282. static char *
  283. reg(paren, flagp)
  284. int paren;            /* Parenthesized? */
  285. int *flagp;
  286. {
  287.     register char *ret;
  288.     register char *br;
  289.     register char *ender;
  290.     register int parno = 0;
  291.     int flags;
  292.  
  293.     *flagp = HASWIDTH;    /* Tentatively. */
  294.  
  295.     /* Make an OPEN node, if parenthesized. */
  296.     if (paren) {
  297.         if (regnpar >= NSUBEXP)
  298.             FAIL("too many ()");
  299.         parno = regnpar;
  300.         regnpar++;
  301.         ret = regnode(OPEN+parno);
  302.     } else
  303.         ret = NULL;
  304.  
  305.     /* Pick up the branches, linking them together. */
  306.     br = regbranch(&flags);
  307.     if (br == NULL)
  308.         return(NULL);
  309.     if (ret != NULL)
  310.         regtail(ret, br);    /* OPEN -> first. */
  311.     else
  312.         ret = br;
  313.     if (!(flags&HASWIDTH))
  314.         *flagp &= ~HASWIDTH;
  315.     *flagp |= flags&SPSTART;
  316.     while (*regparse == '|') {
  317.         regparse++;
  318.         br = regbranch(&flags);
  319.         if (br == NULL)
  320.             return(NULL);
  321.         regtail(ret, br);    /* BRANCH -> BRANCH. */
  322.         if (!(flags&HASWIDTH))
  323.             *flagp &= ~HASWIDTH;
  324.         *flagp |= flags&SPSTART;
  325.     }
  326.  
  327.     /* Make a closing node, and hook it on the end. */
  328.     ender = regnode((paren) ? CLOSE+parno : END);    
  329.     regtail(ret, ender);
  330.  
  331.     /* Hook the tails of the branches to the closing node. */
  332.     for (br = ret; br != NULL; br = regnext(br))
  333.         regoptail(br, ender);
  334.  
  335.     /* Check for proper termination. */
  336.     if (paren && *regparse++ != ')') {
  337.         FAIL("unmatched ()");
  338.     } else if (!paren && *regparse != '\0') {
  339.         if (*regparse == ')') {
  340.             FAIL("unmatched ()");
  341.         } else
  342.             FAIL("junk on end");    /* "Can't happen". */
  343.         /* NOTREACHED */
  344.     }
  345.  
  346.     return(ret);
  347. }
  348.  
  349. /*
  350.  - regbranch - one alternative of an | operator
  351.  *
  352.  * Implements the concatenation operator.
  353.  */
  354. static char *
  355. regbranch(flagp)
  356. int *flagp;
  357. {
  358.     register char *ret;
  359.     register char *chain;
  360.     register char *latest;
  361.     int flags;
  362.  
  363.     *flagp = WORST;        /* Tentatively. */
  364.  
  365.     ret = regnode(BRANCH);
  366.     chain = NULL;
  367.     while (*regparse != '\0' && *regparse != '|' && *regparse != ')') {
  368.         latest = regpiece(&flags);
  369.         if (latest == NULL)
  370.             return(NULL);
  371.         *flagp |= flags&HASWIDTH;
  372.         if (chain == NULL)    /* First piece. */
  373.             *flagp |= flags&SPSTART;
  374.         else
  375.             regtail(chain, latest);
  376.         chain = latest;
  377.     }
  378.     if (chain == NULL)    /* Loop ran zero times. */
  379.         (void) regnode(NOTHING);
  380.  
  381.     return(ret);
  382. }
  383.  
  384. /*
  385.  - regpiece - something followed by possible [*+?]
  386.  *
  387.  * Note that the branching code sequences used for ? and the general cases
  388.  * of * and + are somewhat optimized:  they use the same NOTHING node as
  389.  * both the endmarker for their branch list and the body of the last branch.
  390.  * It might seem that this node could be dispensed with entirely, but the
  391.  * endmarker role is not redundant.
  392.  */
  393. static char *
  394. regpiece(flagp)
  395. int *flagp;
  396. {
  397.     register char *ret;
  398.     register char op;
  399.     register char *next;
  400.     int flags;
  401.  
  402.     ret = regatom(&flags);
  403.     if (ret == NULL)
  404.         return(NULL);
  405.  
  406.     op = *regparse;
  407.     if (!ISMULT(op)) {
  408.         *flagp = flags;
  409.         return(ret);
  410.     }
  411.  
  412.     if (!(flags&HASWIDTH) && op != '?')
  413.         FAIL("*+ operand could be empty");
  414.     *flagp = (op != '+') ? (WORST|SPSTART) : (WORST|HASWIDTH);
  415.  
  416.     if (op == '*' && (flags&SIMPLE))
  417.         reginsert(STAR, ret);
  418.     else if (op == '*') {
  419.         /* Emit x* as (x&|), where & means "self". */
  420.         reginsert(BRANCH, ret);            /* Either x */
  421.         regoptail(ret, regnode(BACK));        /* and loop */
  422.         regoptail(ret, ret);            /* back */
  423.         regtail(ret, regnode(BRANCH));        /* or */
  424.         regtail(ret, regnode(NOTHING));        /* null. */
  425.     } else if (op == '+' && (flags&SIMPLE))
  426.         reginsert(PLUS, ret);
  427.     else if (op == '+') {
  428.         /* Emit x+ as x(&|), where & means "self". */
  429.         next = regnode(BRANCH);            /* Either */
  430.         regtail(ret, next);
  431.         regtail(regnode(BACK), ret);        /* loop back */
  432.         regtail(next, regnode(BRANCH));        /* or */
  433.         regtail(ret, regnode(NOTHING));        /* null. */
  434.     } else if (op == '?') {
  435.         /* Emit x? as (x|) */
  436.         reginsert(BRANCH, ret);            /* Either x */
  437.         regtail(ret, regnode(BRANCH));        /* or */
  438.         next = regnode(NOTHING);        /* null. */
  439.         regtail(ret, next);
  440.         regoptail(ret, next);
  441.     }
  442.     regparse++;
  443.     if (ISMULT(*regparse))
  444.         FAIL("nested *?+");
  445.  
  446.     return(ret);
  447. }
  448.  
  449. /*
  450.  - regatom - the lowest level
  451.  *
  452.  * Optimization:  gobbles an entire sequence of ordinary characters so that
  453.  * it can turn them into a single node, which is smaller to store and
  454.  * faster to run.  Backslashed characters are exceptions, each becoming a
  455.  * separate node; the code is simpler that way and it's not worth fixing.
  456.  */
  457. static char *
  458. regatom(flagp)
  459. int *flagp;
  460. {
  461.     register char *ret;
  462.     int flags;
  463.  
  464.     *flagp = WORST;        /* Tentatively. */
  465.  
  466.     switch (*regparse++) {
  467.     case '^':
  468.         ret = regnode(BOL);
  469.         break;
  470.     case '$':
  471.         ret = regnode(EOL);
  472.         break;
  473.     case '.':
  474.         ret = regnode(ANY);
  475.         *flagp |= HASWIDTH|SIMPLE;
  476.         break;
  477.     case '[': {
  478.             register int clss;
  479.             register int classend;
  480.  
  481.             if (*regparse == '^') {    /* Complement of range. */
  482.                 ret = regnode(ANYBUT);
  483.                 regparse++;
  484.             } else
  485.                 ret = regnode(ANYOF);
  486.             if (*regparse == ']' || *regparse == '-')
  487.                 regc(*regparse++);
  488.             while (*regparse != '\0' && *regparse != ']') {
  489.                 if (*regparse == '-') {
  490.                     regparse++;
  491.                     if (*regparse == ']' || *regparse == '\0')
  492.                         regc('-');
  493.                     else {
  494.                         clss = UCHARAT(regparse-2)+1;
  495.                         classend = UCHARAT(regparse);
  496.                         if (clss > classend+1)
  497.                             FAIL("invalid [] range");
  498.                         for (; clss <= classend; clss++)
  499.                             regc(clss);
  500.                         regparse++;
  501.                     }
  502.                 } else
  503.                     regc(*regparse++);
  504.             }
  505.             regc('\0');
  506.             if (*regparse != ']')
  507.                 FAIL("unmatched []");
  508.             regparse++;
  509.             *flagp |= HASWIDTH|SIMPLE;
  510.         }
  511.         break;
  512.     case '(':
  513.         ret = reg(1, &flags);
  514.         if (ret == NULL)
  515.             return(NULL);
  516.         *flagp |= flags&(HASWIDTH|SPSTART);
  517.         break;
  518.     case '\0':
  519.     case '|':
  520.     case ')':
  521.         FAIL("internal urp");    /* Supposed to be caught earlier. */
  522.         /* NOTREACHED */
  523.         break;
  524.     case '?':
  525.     case '+':
  526.     case '*':
  527.         FAIL("?+* follows nothing");
  528.         /* NOTREACHED */
  529.         break;
  530.     case '\\':
  531.         if (*regparse == '\0')
  532.             FAIL("trailing \\");
  533.         ret = regnode(EXACTLY);
  534.         regc(*regparse++);
  535.         regc('\0');
  536.         *flagp |= HASWIDTH|SIMPLE;
  537.         break;
  538.     default: {
  539.             register int len;
  540.             register char ender;
  541.  
  542.             regparse--;
  543.             len = strcspn(regparse, META);
  544.             if (len <= 0)
  545.                 FAIL("internal disaster");
  546.             ender = *(regparse+len);
  547.             if (len > 1 && ISMULT(ender))
  548.                 len--;        /* Back off clear of ?+* operand. */
  549.             *flagp |= HASWIDTH;
  550.             if (len == 1)
  551.                 *flagp |= SIMPLE;
  552.             ret = regnode(EXACTLY);
  553.             while (len > 0) {
  554.                 regc(*regparse++);
  555.                 len--;
  556.             }
  557.             regc('\0');
  558.         }
  559.         break;
  560.     }
  561.  
  562.     return(ret);
  563. }
  564.  
  565. /*
  566.  - regnode - emit a node
  567.  */
  568. static char *            /* Location. */
  569. regnode(op)
  570. char op;
  571. {
  572.     register char *ret;
  573.     register char *ptr;
  574.  
  575.     ret = regcode;
  576.     if (ret == ®dummy) {
  577.         regsize += 3;
  578.         return(ret);
  579.     }
  580.  
  581.     ptr = ret;
  582.     *ptr++ = op;
  583.     *ptr++ = '\0';        /* Null "next" pointer. */
  584.     *ptr++ = '\0';
  585.     regcode = ptr;
  586.  
  587.     return(ret);
  588. }
  589.  
  590. /*
  591.  - regc - emit (if appropriate) a byte of code
  592.  */
  593. static void
  594. regc(b)
  595. char b;
  596. {
  597.     if (regcode != ®dummy)
  598.         *regcode++ = b;
  599.     else
  600.         regsize++;
  601. }
  602.  
  603. /*
  604.  - reginsert - insert an operator in front of already-emitted operand
  605.  *
  606.  * Means relocating the operand.
  607.  */
  608. static void
  609. reginsert(op, opnd)
  610. char op;
  611. char *opnd;
  612. {
  613.     register char *src;
  614.     register char *dst;
  615.     register char *place;
  616.  
  617.     if (regcode == ®dummy) {
  618.         regsize += 3;
  619.         return;
  620.     }
  621.  
  622.     src = regcode;
  623.     regcode += 3;
  624.     dst = regcode;
  625.     while (src > opnd)
  626.         *--dst = *--src;
  627.  
  628.     place = opnd;        /* Op node, where operand used to be. */
  629.     *place++ = op;
  630.     *place++ = '\0';
  631.     *place++ = '\0';
  632. }
  633.  
  634. /*
  635.  - regtail - set the next-pointer at the end of a node chain
  636.  */
  637. static void
  638. regtail(p, val)
  639. char *p;
  640. char *val;
  641. {
  642.     register char *scan;
  643.     register char *temp;
  644.     register int offset;
  645.  
  646.     if (p == ®dummy)
  647.         return;
  648.  
  649.     /* Find last node. */
  650.     scan = p;
  651.     for (;;) {
  652.         temp = regnext(scan);
  653.         if (temp == NULL)
  654.             break;
  655.         scan = temp;
  656.     }
  657.  
  658.     if (OP(scan) == BACK)
  659.         offset = scan - val;
  660.     else
  661.         offset = val - scan;
  662.     *(scan+1) = (offset>>8)&0377;
  663.     *(scan+2) = offset&0377;
  664. }
  665.  
  666. /*
  667.  - regoptail - regtail on operand of first argument; nop if operandless
  668.  */
  669. static void
  670. regoptail(p, val)
  671. char *p;
  672. char *val;
  673. {
  674.     /* "Operandless" and "op != BRANCH" are synonymous in practice. */
  675.     if (p == NULL || p == ®dummy || OP(p) != BRANCH)
  676.         return;
  677.     regtail(OPERAND(p), val);
  678. }
  679.  
  680. /*
  681.  * regexec and friends
  682.  */
  683.  
  684. /*
  685.  * Global work variables for regexec().
  686.  */
  687. static char *reginput;        /* String-input pointer. */
  688. static char *regbol;        /* Beginning of input, for ^ check. */
  689. static char **regstartp;    /* Pointer to startp array. */
  690. static char **regendp;        /* Ditto for endp. */
  691.  
  692. /*
  693.  * Forwards.
  694.  */
  695. STATIC int regtry();
  696. STATIC int regmatch();
  697. STATIC int regrepeat();
  698.  
  699. #ifdef DEBUG
  700. int regnarrate = 0;
  701. void regdump();
  702. STATIC char *regprop();
  703. #endif
  704.  
  705. /*
  706.  - regexec - match a regexp against a string
  707.  */
  708. int
  709. regexec(prog, string)
  710. register regexp *prog;
  711. register char *string;
  712. {
  713.     register char *s;
  714.     extern char *strchr();
  715.  
  716.     /* Be paranoid... */
  717.     if (prog == NULL || string == NULL) {
  718.         regerror("NULL parameter");
  719.         return(0);
  720.     }
  721.  
  722.     /* Check validity of program. */
  723.     if (UCHARAT(prog->program) != MAGIC) {
  724.         regerror("corrupted program");
  725.         return(0);
  726.     }
  727.  
  728.     /* If there is a "must appear" string, look for it. */
  729.     if (prog->regmust != NULL) {
  730.         s = string;
  731.         while ((s = strchr(s, prog->regmust[0])) != NULL) {
  732.             if (strncmp(s, prog->regmust, prog->regmlen) == 0)
  733.                 break;    /* Found it. */
  734.             s++;
  735.         }
  736.         if (s == NULL)    /* Not present. */
  737.             return(0);
  738.     }
  739.  
  740.     /* Mark beginning of line for ^ . */
  741.     regbol = string;
  742.  
  743.     /* Simplest case:  anchored match need be tried only once. */
  744.     if (prog->reganch)
  745.         return(regtry(prog, string));
  746.  
  747.     /* Messy cases:  unanchored match. */
  748.     s = string;
  749.     if (prog->regstart != '\0')
  750.         /* We know what char it must start with. */
  751.         while ((s = strchr(s, prog->regstart)) != NULL) {
  752.             if (regtry(prog, s))
  753.                 return(1);
  754.             s++;
  755.         }
  756.     else
  757.         /* We don't -- general case. */
  758.         do {
  759.             if (regtry(prog, s))
  760.                 return(1);
  761.         } while (*s++ != '\0');
  762.  
  763.     /* Failure. */
  764.     return(0);
  765. }
  766.  
  767. /*
  768.  - regtry - try match at specific point
  769.  */
  770. static int            /* 0 failure, 1 success */
  771. regtry(prog, string)
  772. regexp *prog;
  773. char *string;
  774. {
  775.     register int i;
  776.     register char **sp;
  777.     register char **ep;
  778.  
  779.     reginput = string;
  780.     regstartp = prog->startp;
  781.     regendp = prog->endp;
  782.  
  783.     sp = prog->startp;
  784.     ep = prog->endp;
  785.     for (i = NSUBEXP; i > 0; i--) {
  786.         *sp++ = NULL;
  787.         *ep++ = NULL;
  788.     }
  789.     if (regmatch(prog->program + 1)) {
  790.         prog->startp[0] = string;
  791.         prog->endp[0] = reginput;
  792.         return(1);
  793.     } else
  794.         return(0);
  795. }
  796.  
  797. /*
  798.  - regmatch - main matching routine
  799.  *
  800.  * Conceptually the strategy is simple:  check to see whether the current
  801.  * node matches, call self recursively to see whether the rest matches,
  802.  * and then act accordingly.  In practice we make some effort to avoid
  803.  * recursion, in particular by going through "ordinary" nodes (that don't
  804.  * need to know whether the rest of the match failed) by a loop instead of
  805.  * by recursion.
  806.  */
  807. static int            /* 0 failure, 1 success */
  808. regmatch(prog)
  809. char *prog;
  810. {
  811.     register char *scan;    /* Current node. */
  812.     char *next;        /* Next node. */
  813.     extern char *strchr();
  814.  
  815.     scan = prog;
  816. #ifdef DEBUG
  817.     if (scan != NULL && regnarrate)
  818.         fprintf(stderr, "%s(\n", regprop(scan));
  819. #endif
  820.     while (scan != NULL) {
  821. #ifdef DEBUG
  822.         if (regnarrate)
  823.             fprintf(stderr, "%s...\n", regprop(scan));
  824. #endif
  825.         next = regnext(scan);
  826.  
  827.         switch (OP(scan)) {
  828.         case BOL:
  829.             if (reginput != regbol)
  830.                 return(0);
  831.             break;
  832.         case EOL:
  833.             if (*reginput != '\0')
  834.                 return(0);
  835.             break;
  836.         case ANY:
  837.             if (*reginput == '\0')
  838.                 return(0);
  839.             reginput++;
  840.             break;
  841.         case EXACTLY: {
  842.                 register int len;
  843.                 register char *opnd;
  844.  
  845.                 opnd = OPERAND(scan);
  846.                 /* Inline the first character, for speed. */
  847.                 if (*opnd != *reginput)
  848.                     return(0);
  849.                 len = strlen(opnd);
  850.                 if (len > 1 && strncmp(opnd, reginput, len) != 0)
  851.                     return(0);
  852.                 reginput += len;
  853.             }
  854.             break;
  855.         case ANYOF:
  856.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) == NULL)
  857.                 return(0);
  858.             reginput++;
  859.             break;
  860.         case ANYBUT:
  861.              if (*reginput == '\0' || strchr(OPERAND(scan), *reginput) != NULL)
  862.                 return(0);
  863.             reginput++;
  864.             break;
  865.         case NOTHING:
  866.             break;
  867.         case BACK:
  868.             break;
  869.         case OPEN+1:
  870.         case OPEN+2:
  871.         case OPEN+3:
  872.         case OPEN+4:
  873.         case OPEN+5:
  874.         case OPEN+6:
  875.         case OPEN+7:
  876.         case OPEN+8:
  877.         case OPEN+9: {
  878.                 register int no;
  879.                 register char *save;
  880.  
  881.                 no = OP(scan) - OPEN;
  882.                 save = reginput;
  883.  
  884.                 if (regmatch(next)) {
  885.                     /*
  886.                      * Don't set startp if some later
  887.                      * invocation of the same parentheses
  888.                      * already has.
  889.                      */
  890.                     if (regstartp[no] == NULL)
  891.                         regstartp[no] = save;
  892.                     return(1);
  893.                 } else
  894.                     return(0);
  895.             }
  896.             /* NOTREACHED */
  897.             break;
  898.         case CLOSE+1:
  899.         case CLOSE+2:
  900.         case CLOSE+3:
  901.         case CLOSE+4:
  902.         case CLOSE+5:
  903.         case CLOSE+6:
  904.         case CLOSE+7:
  905.         case CLOSE+8:
  906.         case CLOSE+9: {
  907.                 register int no;
  908.                 register char *save;
  909.  
  910.                 no = OP(scan) - CLOSE;
  911.                 save = reginput;
  912.  
  913.                 if (regmatch(next)) {
  914.                     /*
  915.                      * Don't set endp if some later
  916.                      * invocation of the same parentheses
  917.                      * already has.
  918.                      */
  919.                     if (regendp[no] == NULL)
  920.                         regendp[no] = save;
  921.                     return(1);
  922.                 } else
  923.                     return(0);
  924.             }
  925.             /* NOTREACHED */
  926.             break;
  927.         case BRANCH: {
  928.                 register char *save;
  929.  
  930.                 if (OP(next) != BRANCH)        /* No choice. */
  931.                     next = OPERAND(scan);    /* Avoid recursion. */
  932.                 else {
  933.                     do {
  934.                         save = reginput;
  935.                         if (regmatch(OPERAND(scan)))
  936.                             return(1);
  937.                         reginput = save;
  938.                         scan = regnext(scan);
  939.                     } while (scan != NULL && OP(scan) == BRANCH);
  940.                     return(0);
  941.                     /* NOTREACHED */
  942.                 }
  943.             }
  944.             /* NOTREACHED */
  945.             break;
  946.         case STAR:
  947.         case PLUS: {
  948.                 register char nextch;
  949.                 register int no;
  950.                 register char *save;
  951.                 register int min;
  952.  
  953.                 /*
  954.                  * Lookahead to avoid useless match attempts
  955.                  * when we know what character comes next.
  956.                  */
  957.                 nextch = '\0';
  958.                 if (OP(next) == EXACTLY)
  959.                     nextch = *OPERAND(next);
  960.                 min = (OP(scan) == STAR) ? 0 : 1;
  961.                 save = reginput;
  962.                 no = regrepeat(OPERAND(scan));
  963.                 while (no >= min) {
  964.                     /* If it could work, try it. */
  965.                     if (nextch == '\0' || *reginput == nextch)
  966.                         if (regmatch(next))
  967.                             return(1);
  968.                     /* Couldn't or didn't -- back up. */
  969.                     no--;
  970.                     reginput = save + no;
  971.                 }
  972.                 return(0);
  973.             }
  974.             /* NOTREACHED */
  975.             break;
  976.         case END:
  977.             return(1);    /* Success! */
  978.             /* NOTREACHED */
  979.             break;
  980.         default:
  981.             regerror("memory corruption");
  982.             return(0);
  983.             /* NOTREACHED */
  984.             break;
  985.         }
  986.  
  987.         scan = next;
  988.     }
  989.  
  990.     /*
  991.      * We get here only if there's trouble -- normally "case END" is
  992.      * the terminating point.
  993.      */
  994.     regerror("corrupted pointers");
  995.     return(0);
  996. }
  997.  
  998. /*
  999.  - regrepeat - repeatedly match something simple, report how many
  1000.  */
  1001. static int
  1002. regrepeat(p)
  1003. char *p;
  1004. {
  1005.     register int count = 0;
  1006.     register char *scan;
  1007.     register char *opnd;
  1008.  
  1009.     scan = reginput;
  1010.     opnd = OPERAND(p);
  1011.     switch (OP(p)) {
  1012.     case ANY:
  1013.         count = strlen(scan);
  1014.         scan += count;
  1015.         break;
  1016.     case EXACTLY:
  1017.         while (*opnd == *scan) {
  1018.             count++;
  1019.             scan++;
  1020.         }
  1021.         break;
  1022.     case ANYOF:
  1023.         while (*scan != '\0' && strchr(opnd, *scan) != NULL) {
  1024.             count++;
  1025.             scan++;
  1026.         }
  1027.         break;
  1028.     case ANYBUT:
  1029.         while (*scan != '\0' && strchr(opnd, *scan) == NULL) {
  1030.             count++;
  1031.             scan++;
  1032.         }
  1033.         break;
  1034.     default:        /* Oh dear.  Called inappropriately. */
  1035.         regerror("internal foulup");
  1036.         count = 0;    /* Best compromise. */
  1037.         break;
  1038.     }
  1039.     reginput = scan;
  1040.  
  1041.     return(count);
  1042. }
  1043.  
  1044. /*
  1045.  - regnext - dig the "next" pointer out of a node
  1046.  */
  1047. static char *
  1048. regnext(p)
  1049. register char *p;
  1050. {
  1051.     register int offset;
  1052.  
  1053.     if (p == ®dummy)
  1054.         return(NULL);
  1055.  
  1056.     offset = NEXT(p);
  1057.     if (offset == 0)
  1058.         return(NULL);
  1059.  
  1060.     if (OP(p) == BACK)
  1061.         return(p-offset);
  1062.     else
  1063.         return(p+offset);
  1064. }
  1065.  
  1066. #ifdef DEBUG
  1067.  
  1068. STATIC char *regprop();
  1069.  
  1070. /*
  1071.  - regdump - dump a regexp onto stdout in vaguely comprehensible form
  1072.  */
  1073. void
  1074. regdump(r)
  1075. regexp *r;
  1076. {
  1077.     register char *s;
  1078.     register char op = EXACTLY;    /* Arbitrary non-END op. */
  1079.     register char *next;
  1080.     extern char *strchr();
  1081.  
  1082.  
  1083.     s = r->program + 1;
  1084.     while (op != END) {    /* While that wasn't END last time... */
  1085.         op = OP(s);
  1086.         printf("%2d%s", s-r->program, regprop(s));    /* Where, what. */
  1087.         next = regnext(s);
  1088.         if (next == NULL)        /* Next ptr. */
  1089.             printf("(0)");
  1090.         else 
  1091.             printf("(%d)", (s-r->program)+(next-s));
  1092.         s += 3;
  1093.         if (op == ANYOF || op == ANYBUT || op == EXACTLY) {
  1094.             /* Literal string, where present. */
  1095.             while (*s != '\0') {
  1096.                 putchar(*s);
  1097.                 s++;
  1098.             }
  1099.             s++;
  1100.         }
  1101.         putchar('\n');
  1102.     }
  1103.  
  1104.     /* Header fields of interest. */
  1105.     if (r->regstart != '\0')
  1106.         printf("start `%c' ", r->regstart);
  1107.     if (r->reganch)
  1108.         printf("anchored ");
  1109.     if (r->regmust != NULL)
  1110.         printf("must have \"%s\"", r->regmust);
  1111.     printf("\n");
  1112. }
  1113.  
  1114. /*
  1115.  - regprop - printable representation of opcode
  1116.  */
  1117. static char *
  1118. regprop(op)
  1119. char *op;
  1120. {
  1121.     register char *p;
  1122.     static char buf[50];
  1123.  
  1124.     (void) strcpy(buf, ":");
  1125.  
  1126.     switch (OP(op)) {
  1127.     case BOL:
  1128.         p = "BOL";
  1129.         break;
  1130.     case EOL:
  1131.         p = "EOL";
  1132.         break;
  1133.     case ANY:
  1134.         p = "ANY";
  1135.         break;
  1136.     case ANYOF:
  1137.         p = "ANYOF";
  1138.         break;
  1139.     case ANYBUT:
  1140.         p = "ANYBUT";
  1141.         break;
  1142.     case BRANCH:
  1143.         p = "BRANCH";
  1144.         break;
  1145.     case EXACTLY:
  1146.         p = "EXACTLY";
  1147.         break;
  1148.     case NOTHING:
  1149.         p = "NOTHING";
  1150.         break;
  1151.     case BACK:
  1152.         p = "BACK";
  1153.         break;
  1154.     case END:
  1155.         p = "END";
  1156.         break;
  1157.     case OPEN+1:
  1158.     case OPEN+2:
  1159.     case OPEN+3:
  1160.     case OPEN+4:
  1161.     case OPEN+5:
  1162.     case OPEN+6:
  1163.     case OPEN+7:
  1164.     case OPEN+8:
  1165.     case OPEN+9:
  1166.         sprintf(buf+strlen(buf), "OPEN%d", OP(op)-OPEN);
  1167.         p = NULL;
  1168.         break;
  1169.     case CLOSE+1:
  1170.     case CLOSE+2:
  1171.     case CLOSE+3:
  1172.     case CLOSE+4:
  1173.     case CLOSE+5:
  1174.     case CLOSE+6:
  1175.     case CLOSE+7:
  1176.     case CLOSE+8:
  1177.     case CLOSE+9:
  1178.         sprintf(buf+strlen(buf), "CLOSE%d", OP(op)-CLOSE);
  1179.         p = NULL;
  1180.         break;
  1181.     case STAR:
  1182.         p = "STAR";
  1183.         break;
  1184.     case PLUS:
  1185.         p = "PLUS";
  1186.         break;
  1187.     default:
  1188.         regerror("corrupted opcode");
  1189.         break;
  1190.     }
  1191.     if (p != NULL)
  1192.         (void) strcat(buf, p);
  1193.     return(buf);
  1194. }
  1195. #endif
  1196.  
  1197. /*
  1198.  * The following is provided for those people who do not have strcspn() in
  1199.  * their C libraries.  They should get off their butts and do something
  1200.  * about it; at least one public-domain implementation of those (highly
  1201.  * useful) string routines has been published on Usenet.
  1202.  */
  1203. #ifdef STRCSPN
  1204. /*
  1205.  * strcspn - find length of initial segment of s1 consisting entirely
  1206.  * of characters not from s2
  1207.  */
  1208.  
  1209. static int
  1210. strcspn(s1, s2)
  1211. char *s1;
  1212. char *s2;
  1213. {
  1214.     register char *scan1;
  1215.     register char *scan2;
  1216.     register int count;
  1217.  
  1218.     count = 0;
  1219.     for (scan1 = s1; *scan1 != '\0'; scan1++) {
  1220.         for (scan2 = s2; *scan2 != '\0';)    /* ++ moved down. */
  1221.             if (*scan1 == *scan2++)
  1222.                 return(count);
  1223.         count++;
  1224.     }
  1225.     return(count);
  1226. }
  1227. #endif
  1228.